import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const types = {
  SET_IS_AUTNENTIATED: 'SET_IS_AUTNENTIATED', // 是否认证通过
  SET_USER: 'SET_USER' // 用户信息
}
const state = {
  isAutnenticated:  sessionStorage["isAutnenticated"] ? JSON.parse(sessionStorage["user"]) :false,  // 是否认证
  user: sessionStorage["user"] ? JSON.parse(sessionStorage["user"]) : {} // 存储用户信息
}
const getters = {
  isAutnenticated: state => state.isAutnenticated,
  user: state => state.user
}
const mutations = {
  [types.SET_IS_AUTNENTIATED](state, isAutnenticated) {
    if (isAutnenticated) state.isAutnenticated = isAutnenticated;
    else state.isAutnenticated = false;
  },
  [types.SET_USER](state, user) {
    if (user)
      state.user = user
    else
      state.user = {}
  }
}
const actions = {
  setIsAutnenticated: ({ commit }, isAutnenticated) => {
    commit(types.SET_IS_AUTNENTIATED, isAutnenticated)
    sessionStorage.setItem("isAutnenticated", JSON.stringify(isAutnenticated))
  },
  setUser: ({ commit }, user) => {
    commit(types.SET_USER, user)
    sessionStorage.setItem("user", JSON.stringify(user))
  },
  clearCurrentState: ({ commit }) => {
    commit(types.SET_IS_AUTNENTIATED, false)
    sessionStorage.removeItem("isAutnenticated")
    commit(types.SET_USER, {})
    sessionStorage.removeItem("user")
  }
}
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})
